# -*- coding: utf-8 -*-
import logging

from django_pandas.io import read_frame
from rest_framework import status, serializers
from rest_framework.decorators import action
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet, ModelViewSet

from django_package.application.models import TableModel, DataFrameModel, ExampleModel
from django_package.application.serializers import DataFrameModelSerializer, DataFrameSerializer, TableResponse, \
    TableRequest
from django_service.messages import default_response

logger = logging.getLogger(__name__)


class DataFrameModelViewSet(ModelViewSet):
    authentication_classes = []
    permission_classes = []

    queryset = DataFrameModel.objects.filter(df_type='df')

    serializer_class = serializers.Serializer

    # def get_queryset(self):
    #     return self.queryset.filter(drf_user=self.request.user.username)

    @action(methods=['get'], detail=False)
    def read_frame(self, *args, **kwargs):
        # DataFrameSer(self.request)

        # qs
        qs = self.filter_queryset(self.get_queryset())

        # df
        df = read_frame(qs)

        serializer = DataFrameModelSerializer(df.to_dict(orient='records'), many=True)

        return Response(data=serializer.data,
                        status=status.HTTP_200_OK)


class ExampleModelViewSet(ModelViewSet):
    queryset = ExampleModel.objects.filter(status=1)

    @action(methods=['get'], detail=False)
    def list_example(self, *args, **kwargs):
        logger.info(f'username:{self.request.user.username}')
        return Response(data=default_response(),
                        status=status.HTTP_200_OK)

    @action(methods=['post'], detail=False)
    def post_example(self, *args, **kwargs):
        logger.info(f'username:{self.request.user.username}')
        return Response(data=default_response(),
                        status=status.HTTP_200_OK)

    @action(methods=['put'], detail=True)
    def put_example(self, *args, **kwargs):
        logger.info(f'username:{self.request.user.username}')
        return Response(data=default_response(),
                        status=status.HTTP_200_OK)

    @action(methods=['get'], detail=True)
    def get_example(self, *args, **kwargs):
        logger.info(f'username:{self.request.user.username}')
        return Response(data=default_response(),
                        status=status.HTTP_200_OK)


class TableView(ModelViewSet):
    """
    通用表格模板视图
    """
    queryset = TableModel.objects.filter()

    filter_backends = [SearchFilter, OrderingFilter]
    search_fields = ['portfolio_code', 'portfolio_name']
    ordering_fields = ['portfolio_code']

    @action(methods=['post'], detail=False)
    def handle(self, *args, **kwargs):
        request = TableRequest(self.request.data)
        request.is_valid(raise_exception=True)
        t_code = request.validated_data['t_code']
        qs = self.get_queryset().filter(t_code=t_code)
        response = TableResponse(qs)
        return Response(data=response.data,
                        status=status.HTTP_200_OK)

    @action(methods=['post'], detail=False)
    def validate(self, *args, **kwargs):
        # from rest_framework.exceptions import ValidationError
        from django.core.exceptions import ValidationError
        # ValidationError
        logger.info(self.request.data)
        return Response(data=default_response(),
                        status=status.HTTP_200_OK)
